package com.milepost.workflow.pushmsg.ctrl;

import com.milepost.workflow.pushmsg.entity.WorkWxMessageEntity;
import com.milepost.workflow.response.Response;
import com.milepost.workflow.response.ResponseHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Map;

/**
 * @author huarf
 * @Description
 * @create 2022-04-05 22:54
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/pushMsg")
public class PushMsgCtrl {

    private final RestTemplate restTemplate;

    @Value("${work-wx-msg.push-url}")
    private String pushUrl;

    /**
     * 推送消息
     *
     * @param workWxMessageEntity
     * @return
     */
    @PostMapping("/push")
    public Response<Map<String, Object>> push(@RequestBody WorkWxMessageEntity workWxMessageEntity, HttpServletRequest request) {

        Response<Map<String, Object>> response = null;

        try {
            RequestEntity<WorkWxMessageEntity> requestEntity = RequestEntity
                    .post(URI.create(pushUrl))
                    .accept(MediaType.APPLICATION_JSON)
                    .header(HttpHeaders.COOKIE, request.getHeader(HttpHeaders.COOKIE))
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(workWxMessageEntity);

            ParameterizedTypeReference<Response<Map<String, Object>>> parameterizedTypeReference = new ParameterizedTypeReference<Response<Map<String, Object>>>() {};
            ResponseEntity<Response<Map<String, Object>>> responseEntity = restTemplate.exchange(requestEntity, parameterizedTypeReference);
            response = responseEntity.getBody();

        } catch (Exception e) {
            log.error("推送消息异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        }

        return response;
    }

}
